IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'MD3.f_GetForeignKeys'))
DROP FUNCTION MD3.f_GetForeignKeys
GO

CREATE FUNCTION MD3.f_GetForeignKeys
	 ( 
		 @SchemaName SYSNAME
		,@TableName SYSNAME 
	 )
RETURNS @FK  TABLE   
(    
    ForeignKeyName		SYSNAME NOT NULL,   
    SchemaName			SYSNAME NOT NULL, 
    TableName			SYSNAME NOT NULL,
    KeyColumns			VARCHAR(MAX)NOT NULL,
    ParentSchemaName	SYSNAME NOT NULL, 
    ParentTableName		SYSNAME NOT NULL,
    ParentKeyColumns	VARCHAR(MAX)NOT NULL,
    IsDisabled          BIT NOT NULL,
    IsNotTrusted        BIT NOT NULL,
    IsNotForReplication BIT NOT NULL,
    IsDeleteCascade     BIT NOT NULL,
    IsUpdateCascade     BIT NOT NULL
)    
AS  
BEGIN
    
	DECLARE @FullName NVARCHAR(260)
    SET @FullName = @SchemaName + '.'	+ @TableName
    
	INSERT INTO @FK 
    SELECT  fk.name,OBJECT_SCHEMA_NAME(fk.parent_object_id), 
			OBJECT_NAME(fk.parent_object_id),
			REVERSE(SUBSTRING(REVERSE((
				SELECT cp.name + ','
				FROM
				sys.foreign_key_columns fkc
					INNER JOIN sys.columns cp 
						ON fkc.parent_object_id = cp.object_id 
							AND fkc.parent_column_id = cp.column_id
				WHERE fkc.constraint_object_id = fk.object_id 
					FOR XML PATH('')
				)), 2, 8000)) AS FKColumns,
			OBJECT_SCHEMA_NAME(fk.referenced_object_id),
			OBJECT_NAME(fk.referenced_object_id),
			REVERSE(SUBSTRING(REVERSE((
				SELECT cr.name + ','
				FROM sys.foreign_key_columns fkc
					 INNER JOIN sys.columns cr
						 ON fkc.referenced_object_id = cr.object_id 
							AND fkc.referenced_column_id = cr.column_id
				WHERE fkc.constraint_object_id = fk.object_id
					FOR XML PATH('')
				)), 2, 8000))AS ReferencedColumns,
            fk.is_disabled,
            fk.is_not_trusted,
            fk.is_not_for_replication,
            fk.delete_referential_action,
            fk.update_referential_action
      FROM sys.foreign_keys fk
	  WHERE  fk.parent_object_id = OBJECT_ID(@FullName)

   RETURN
   
END
GO
